//
//  MicroAnimTool.swift
//  TinyUI
//
//  Created by 徐涛 on 2020/3/26.
//  Copyright © 2020 葛晓良. All rights reserved.
//

import UIKit

@objc protocol MicroAnimToolDelegate {
    func animationIsDidStop(isStop:Bool)
}



let ManmationKey = "ManmationKey"



class MicroAnimTool: NSObject ,CAAnimationDelegate{
    private var beiLiyaPath:UIBezierPath?
    var animLayer:CALayer?
    weak var toolDelegate:MicroAnimToolDelegate?
    var animTime:CGFloat=0.2
    
    override init() {
        super.init()
        
    }
    
    func animateParabola(startRect: CGRect,  begView:UIView , superView view:UIView ,  lastPoint:CGPoint ,startToEndSpacePercentage per:NSInteger, animationValue:CGFloat)  {
        
        let image=self.cutToImage(view: begView)
        let imageView=UIImageView.init(frame: CGRect(x: 0, y: 0, width: begView.bounds.width, height: begView.bounds.height))
        imageView.image=image
        if animLayer == nil {
            animLayer = CALayer.init()
            if #available(iOS 14.0, *) {
                imageView.layer.display()
            }
            animLayer?.contents=imageView.layer.contents
            animLayer?.contentsGravity=CALayerContentsGravity.resizeAspectFill
            
            animLayer!.bounds=startRect
            animLayer?.masksToBounds = true
            animLayer?.position = CGPoint(x:startRect.origin.x+imageView.bounds.width/2.0, y:startRect.origin.y+imageView.bounds.height/2.0)
            view.layer.addSublayer(animLayer!)
            
            beiLiyaPath=UIBezierPath.init()
            beiLiyaPath?.move(to: animLayer!.position)
            beiLiyaPath?.addLine(to: lastPoint)
            
        }
        groupAnimation(animationValue: animationValue)
    }
    
    private func groupAnimation(animationValue:CGFloat) {
        let  animation:CAKeyframeAnimation = CAKeyframeAnimation.init(keyPath: "position")
        animation.path=beiLiyaPath?.cgPath
        
        let group:CAAnimationGroup = CAAnimationGroup.init()
        group.animations=[animation]
        group.duration=Double(animTime)
        group.isRemovedOnCompletion=false
        group.fillMode=CAMediaTimingFillMode.forwards
        group.delegate=self
        animLayer?.add(group, forKey: ManmationKey)
    }
    
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if anim == animLayer?.animation(forKey: ManmationKey) {
            animLayer?.removeFromSuperlayer()
            animLayer = nil
            self.toolDelegate?.animationIsDidStop(isStop: flag)
        }
    }
    
    func cutToImage(view:UIView) -> UIImage {
        UIGraphicsBeginImageContext(view.bounds.size)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
    
    
}
